Day 4: Dictionaries
Creating and Accessing Dictionaries
A dictionary is a collection of key-value pairs.
student = {
"name": "Alice",
"age": 20,
"grade": "A"
}
print(student["name"]) # Alice
print(student.get("email", "N/A")) # N/A (default value)
Key Methods
| Method | Description | Example |
|---|---|---|
keys() | List of keys | student.keys() |
values() | List of values | student.values() |
items() | Key-value pairs | student.items() |
get(k, d) | Safe access | student.get("age", 0) |
update(d) | Merge | student.update({"age": 21}) |
pop(k) | Delete by key | student.pop("grade") |
Iterating Over Dictionaries
scores = {"math": 90, "english": 85, "science": 92}
for subject, score in scores.items():
print(f"{subject}: {score} points")
# math: 90 points
# english: 85 points
# science: 92 points
Nested Dictionaries
school = {
"class_1": {"teacher": "Mr. Kim", "students": 30},
"class_2": {"teacher": "Ms. Lee", "students": 28},
}
print(school["class_1"]["teacher"]) # Mr. Kim
Today’s Exercises
- Write a program that counts word frequencies (input a sentence -> count occurrences of each word).
- Create a function that merges two dictionaries, adding values for matching keys.
- Find the student with the highest average score from a student grades dictionary.